﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.IO;

namespace Intel.Server.WCFLibrary
{
    // 注意: 使用“重构”菜单上的“重命名”命令，可以同时更改代码和配置文件中的类名“Service1”。
    public class PCHMSService : IPCHMSService
    {
        static PCHMSService()
        {
            Sessions = new SessionManager(Db as IValidator);
        }

        public string RequestSession(string Username, string Password)
        {
           // var session = Sessions.RequestSession(Username, Password);
            return Sessions.RequestSession(Username, Password).SessionId;
        }

        public DateTime? RequestUploadRecords(string SessionId,DataType type)
        {
            Console.WriteLine("Request {1} upload;SessionId={0}", SessionId,type.ToString());
            var session = Sessions[SessionId];
            if (session == null)
            {
                Console.WriteLine("upload request failed;SessionId={0}", SessionId);
            }
            var Date = Db.GetUserLastUploadTime(session.UserId,type);
            Console.WriteLine("{0} upload last time is {1};SessionId={2}", type.ToString(), Date.ToString(), SessionId);
            return Date;
            
        }

        public bool Validate(string Username, string Password)
        {
            
            var r =Sessions.Validate(Username, Password);
            Console.WriteLine("Validate User;username={0};result is {1}", Username, r.ToString());
            return r;
        }

        public void Upload(FileData Data)
        {
            Console.WriteLine("Start Upload; SessionId={0}", Data.SessionId.ToString());
            string FilePath;
            DirectoryInfo info = new DirectoryInfo("D:/temp");
            if (!info.Exists)
                info.Create();
            if (!info.Exists)
                throw new SystemException("Can not open temp directory");
            FilePath = "d:/temp/" + Data.SessionId + Data.type.ToString();
            try
            {
                var session = Sessions[Data.SessionId];
                if (session == null)
                {
                    Console.WriteLine("SessionId invalid;SessionId={0}", Data.SessionId);
                    return;
                }
                if (!session.AllowedMouseUpload && !session.AllowedKeyUpload)
                {

                }
                Stream s = Data.Data;
                int count;
                FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate);
                byte[] buffer = new byte[4096];
                while ((count = s.Read(buffer, 0, 4096)) > 0)
                {
                    fs.Write(buffer, 0, count);
                }
                fs.Close();
                s.Close();
                Console.WriteLine("DataAccepted; SesionId={0}", Data
                    .SessionId.ToString());
                Db.LoadDataInfile(FilePath, Data.type, session.UserId);
                Console.WriteLine("Upload Finished;SessionId={0}", Data.SessionId.ToString());
            }
            catch (System.Exception ex)
            {
                File.Delete(FilePath);
                Console.WriteLine(ex.Message + "SessionId =" + Data.SessionId.ToString());
                throw new SystemException(ex.Message);
            }
            finally
            {
                File.Delete(FilePath);
            }
            
        }

        public UserInfo GetInfo(string SessionId)
        {
            var r = Sessions[SessionId];
            if (r != null)
            {
                var info = new UserInfo();
                info.Email = "aaa";
                info.Name = "bbb";
                return info;
            }
            else
                throw new SystemException("SessinId invalid");
        }

        private static MysqlDb Db = Globle.Db;

        private static SessionManager Sessions;
    }
}
